/**
 * https://leetcode-cn.com/problems/basic-calculator/
 * @param {string} s
 * @return {number}
 */
var calculate = function (s) {
  let n = s.length;
  let sign = 1;
  let ops = [1];
  let result = 0;
  let i = 0;
  while (i < n) {
    if (s[i] == " ") {
      i++;
    } else if (s[i] == "+") {
      sign = ops[ops.length - 1];
      i++;
    } else if (s[i] == "-") {
      sign = -ops[ops.length - 1];
      i++;
    } else if (s[i] == "(") {
      ops.push(sign);
      i++;
    } else if (s[i] == ")") {
      ops.pop();
      i++;
    } else {
      let num = 0;
      while (i < n && !isNaN(Number(s[i])) && s[i] !== " ") {
        num = num * 10 + s[i].charCodeAt() - "0".charCodeAt();
        i++;
      }
      result += num * sign;
    }
  }
  return result;
};
